package com.zcy.dynamic;

import org.springframework.util.FastByteArrayOutputStream;

import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import java.io.*;
import java.net.URI;
import java.net.URL;

/**
 * 自定义java class文件载体
 */
public class JavaClassObject extends SimpleJavaFileObject {
 
    protected final ByteArrayOutputStream bos =
        new ByteArrayOutputStream();
 
 
    public JavaClassObject(String name, Kind kind) {
        super(URI.create("string:///" + name.replace('.', '/')
            + kind.extension), kind);
    }
 
 
    public byte[] getBytes() {
        return bos.toByteArray();
    }

    public void writeToFile(String path){
        org.springframework.util.FastByteArrayOutputStream fbaos = new FastByteArrayOutputStream();
        try {
            fbaos.write(this.getBytes(),0,this.getBytes().length);
            fbaos.writeTo(new FileOutputStream(new File(path)));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fbaos.flush();
                fbaos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    @Override
    public OutputStream openOutputStream() throws IOException {
        return bos;
    }
}